package com.qzdatasoft.ratelimit.bean;

import lombok.Builder;
import lombok.Getter;

@Builder
@Getter
public class ResourceKey implements AutoCloseable{
    // resource Key 分隔符(兼容 Redis 考虑)
    private static final String DELIMITER = ":";
    @Builder.Default
    private int priority = 4;
    private String dimension;
    private String urlPattern;
    private String ip;
    private String user;

    public static ResourceKey parseKey(String resourceKey) {
        String[] parts = resourceKey.split(":");
        if (parts.length >= 4 && parts[0].toLowerCase().equals("ip_user")) {
            return ResourceKey.builder().dimension(parts[0]).priority(4).urlPattern(parts[3]).ip(parts[1]).user(parts[2]).build();
        } else if (parts.length == 3 && parts[0].toLowerCase().equals("ip")) {
            return ResourceKey.builder().dimension(parts[0]).priority(3).urlPattern(parts[2]).ip(parts[1]).build();
        } else if (parts.length == 3 && parts[0].toLowerCase().equals("user")) {
            return ResourceKey.builder().dimension(parts[0]).priority(2).urlPattern(parts[2]).user(parts[1]).build();
        } else if (parts.length == 2 && parts[0].toLowerCase().equals("global")) {
            return ResourceKey.builder().dimension(parts[0]).priority(2).urlPattern(parts[1]).build();
        }
        throw new IllegalArgumentException("Invalid resource key: " + resourceKey);
    }

    // resource key 4 种组成规则：[[ip:][user:]]url
    public String buildKey() {
        if (this.priority == 4 && this.dimension.equals("ip_user")) {
            return this.dimension + DELIMITER + this.ip + DELIMITER + this.user + DELIMITER + this.urlPattern;
        } else if (this.priority == 3 && this.dimension.equals("ip")) {
            return this.dimension + DELIMITER + this.ip + DELIMITER + this.urlPattern;
        } else if (this.priority == 2 && this.dimension.equals("user")) {
            return this.dimension + DELIMITER + this.user + DELIMITER + this.urlPattern;
        } else if (this.priority == 1 && this.dimension.equals("global")){
            return "global" + DELIMITER + this.urlPattern;
        }
        throw new IllegalArgumentException("Invalid resource key components");
    }

    @Override
    public void close() throws Exception {
        // No resources to close
    }
}
